package cn.yunyichina.provider.base.service.impl;

import cn.yunyichina.provider.base.dao.DepartmentDao;
import cn.yunyichina.provider.base.dao.DoctorDao;
import cn.yunyichina.provider.base.entity.Department;
import cn.yunyichina.provider.base.entity.Doctor;
import cn.yunyichina.provider.base.vo.DepartmentVo;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.convert.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by JoeZ on 2016/9/19.
 */
@Service
public class DepartmentServiceImpl {

    @Autowired
    private DepartmentDao departmentDao;

    @Autowired
    private DoctorDao doctorDao;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 科室列表查询
     * @param data
     * @return
     */
    public Response listDepartment(String data) {

        Response response = new Response();
        Map<String, Object> result = new HashMap<>();

        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
        String hospitalId = maps.get("hospital_id");
        String branchCode = maps.get("branch_code");
        String page_num = maps.get("page_num");
        String page_size = maps.get("page_size");

        Department dept = new Department();
        dept.setHospitalId(hospitalId);
        dept.setBranchCode(branchCode);
        dept.setDelStatus(0);

        List<DepartmentVo> depts = null;
        PageInfo pageInfo = new PageInfo();

        pageInfo.setPageNum(Integer.valueOf(page_num));
        pageInfo.setPageSize(Integer.valueOf(page_size));

        //取总记录数
        depts = departmentDao.selectDept(pageInfo , hospitalId);

        String deptCount = departmentDao.selectDeptCount(hospitalId);

        pageInfo.setTotal(Long.valueOf(deptCount));
        pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());

        result.put("list" , depts);
        result.put("page_info" , pageInfo);
        response.setResult(JsonUtils.toJsonString(result));

        response.setResultCodeAndMessage("0", "查询成功!");

        return response;

    }


    /**
     * 添加科室
     * @param data
     * @return
     */
    public Response addDepartment(String data) {

        Response response = new Response();

        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
        String hospitalId = maps.get("hospital_id");
        String hospitalName = maps.get("hospital_name");
        String hospitalCode = maps.get("hospital_code");
        String patdeptId = maps.get("patdept_id");
        String deptName = maps.get("dept_name");
        String deptCode = maps.get("dept_code");
        String type = maps.get("type");
        String disc = maps.get("disc");


        Department dept = new Department();
        dept.setName(deptName);
        dept.setDelStatus(0);

//        //查询是否存在相同科室名称
//        List<Department> departments = departmentDao.selectDeptByName(dept);
//        if(departments.size() > 0){
//            response.setResultCodeAndMessage("1", "新增失败，存在相同名称的科室!");
//            return response;
//        }

        dept.setId(PKGenerator.generateId());
        dept.setHospitalId(hospitalId);
        dept.setHospitalName(hospitalName);
        dept.setHospitalCode(hospitalCode);
        dept.setDeptCode(deptCode);
        dept.setType(Integer.valueOf(type));
        dept.setDisc(disc);
        dept.setCreatedTime(simpleDateFormat.format(new Date()));
        dept.setUpdateTime(simpleDateFormat.format(new Date()));

        //存二级科室
        if(StringUtils.isNotBlank(patdeptId)){
            dept.setPid(patdeptId);
        }

        departmentDao.insert(dept);

        response.setResultCodeAndMessage("0", "添加成功!");
        response.setResult(JsonUtils.toJsonString(dept));

        return response;

    }



    /**
     * 修改科室
     * @param data
     * @return
     */
    public Response updateDepartment(String data) {

        Response response = new Response();

        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
        String hospitalId = maps.get("hospital_id");
        String patdeptId = maps.get("patdept_id");
        String id = maps.get("dept_id");
        String deptName = maps.get("dept_name");
        String deptCode = maps.get("dept_code");
        String type = maps.get("type");
        String disc = maps.get("disc");


        Department dept = new Department();
        dept.setDelStatus(0);
        dept.setName(deptName);

        //查询是否存在相同科室名称
        List<Department> departments = departmentDao.selectDeptByName(dept);
        if(departments.size() > 0){
            Department department = departmentDao.selectById(id);
            if(!deptName.equals(department.getName())){
                response.setResultCodeAndMessage("1", "修改失败，存在相同名称的科室!");
                return response;
            }
        }

        dept.setId(id);
        dept.setHospitalId(hospitalId);
        dept.setDeptCode(deptCode);
        dept.setType(Integer.valueOf(type));
        dept.setDisc(disc);
        dept.setUpdateTime(simpleDateFormat.format(new Date()));

        //修改二级科室
        if(StringUtils.isNotBlank(patdeptId)){
            dept.setPid(patdeptId);
        }else{
            dept.setPid("0");
        }

        departmentDao.update(dept);

        response.setResultCodeAndMessage("0", "修改成功!");
        response.setResult(JsonUtils.toJsonString(dept));

        return response;

    }


    /**
     * 删除科室
     * @param data
     * @return
     */
    public Response deleteDepartment(String data) {
        Response response = new Response();
        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
        String id = maps.get("dept_id");

        //是否存在医生关联
        Doctor doctor = new Doctor();
        doctor.setDepartmentId(id);
        doctor.setDelStatus(0);
        List<Doctor> doctors = doctorDao.select(doctor);
        if(doctors.size() > 0){
            response.setResultCodeAndMessage("1", "删除失败，存在医生关联。请先删除医生关联关系!");
            return response;
        }


        //是否存在二级科室
        Department department = new Department();
        department.setPid(id);
        department.setDelStatus(0);
        List<Department> departments = departmentDao.select(department);
        if(departments.size() > 0){
            response.setResultCodeAndMessage("1", "删除失败，存在二级科室关联。请先删除该科室下的二级科室!");
            return response;
        }

        //删除
        Department dept = new Department();
        dept.setId(id);
        dept.setDelStatus(1);
        departmentDao.update(dept);

        response.setResultCodeAndMessage("0", "删除成功!");
        response.setResult(JsonUtils.toJsonString(null));

        return response;

    }


    /**
     * 根据ID查询科室
     * @param data
     * @return
     */
    public Response findDepartment(String data) {

        Response response = new Response();
        Map<String, Object> result = new HashMap<>();

        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
        String deptId = maps.get("dept_id");
        Department department = departmentDao.selectById(deptId);
        response.setResult(JsonUtils.toJsonString(department));
        response.setResultCodeAndMessage("0", "查询成功!");

        return response;

    }


    /**
     * 编辑科室 - 一级科室列表展示
     * @param data
     * @return
     */
    public Response oneDepartmentLevel(String data) {

        Response response = new Response();
        Map<String, Object> result = new HashMap<>();

        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
        String hospitalId = maps.get("hospital_id");
        String deptId = maps.get("dept_id");

        List<Department> departments = null;
        if(StringUtils.isBlank(deptId)){
            departments = departmentDao.selectGetOneDeptEx(hospitalId);
        }else{
            departments = departmentDao.selectGetOneDept(hospitalId , deptId);
        }
        response.setResult(JsonUtils.toJsonString(departments));
        response.setResultCodeAndMessage("0", "查询成功!");

        return response;

    }


    /**
     * 医生条件搜索医院ID查询所有二级科室
     * @param data
     * @return
     */
    public Response twoDepartmentLevel(String data) {

        Response response = new Response();
        Map<String, Object> result = new HashMap<>();

        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
        String hospitalId = maps.get("hospital_id");
        Department dept = new Department();
        dept.setDelStatus(0);
        dept.setHospitalId(hospitalId);
        List<Department> departments = departmentDao.select(dept);

        response.setResult(JsonUtils.toJsonString(departments));
        response.setResultCodeAndMessage("0", "查询成功!");

        return response;

    }


    /**
     * 医生编辑根据医院ID查询所有一级科室、二级科室
     * @param data
     * @return
     */
    public Response getDepartment(String data) {

        Response response = new Response();
        Map<String, Object> result = new HashMap<>();

        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
        String hospitalId = maps.get("hospital_id");
        Department dept = new Department();
        dept.setDelStatus(0);
        dept.setHospitalId(hospitalId);
        List<Department> departments = departmentDao.select(dept);

//        for (Department de : departments) {
//            List<Department> twoDept = departmentDao.selectGetDept(hospitalId, de.getId());
//            de.setTwoDepts(twoDept);
//        }

        response.setResult(JsonUtils.toJsonString(departments));
        response.setResultCodeAndMessage("0", "查询成功!");

        return response;

    }

}
